package com.yinhe.music.yhmusic.dialog.more;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusListObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.adapter.MoreDialogAdapter;
import com.yinhe.music.yhmusic.album.info.AlbumInfoActivity;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BaseServiceDialogFragment;
import com.yinhe.music.yhmusic.comment.CommentListActivity;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.dialog.BuyDialog;
import com.yinhe.music.yhmusic.dialog.DeleteDialog;
import com.yinhe.music.yhmusic.dialog.collect.CollectionDialog;
import com.yinhe.music.yhmusic.downmusic.DownloadStatus;
import com.yinhe.music.yhmusic.login.LoginRegisterActivity;
import com.yinhe.music.yhmusic.manager.IMusicManagerContract;
import com.yinhe.music.yhmusic.manager.MusicManagerPresenter;
import com.yinhe.music.yhmusic.model.MoreBean;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.model.MvsInfo;
import com.yinhe.music.yhmusic.music.PlayUtils;
import com.yinhe.music.yhmusic.personal.BuyMusicActivity;
import com.yinhe.music.yhmusic.singer.info.SingerInfoActivity;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.ToastUtils;
import com.yinhe.music.yhmusic.utils.UmengEventUtils;
import com.yinhe.music.yhmusic.utils.ViewUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.yinhe.music.yhmusic.constants.IConstants.ICON;
import static com.yinhe.music.yhmusic.constants.IConstants.ICON_NAME;

/**
 * @author 何晓华
 */
public class MoreDialog extends BaseServiceDialogFragment implements IMusicManagerContract.IMusicManagerView,
        IMoreDialogContract.IMoreDialogView {

    @BindView(R.id.more_name)
    TextView moreName;
    @BindView(R.id.more_button)
    Button moreButton;
    @BindView(R.id.login_layout)
    LinearLayout loginLayout;
    @BindView(R.id.new_more_recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.cancel)
    TextView cancel;

    Unbinder unbinder;

    private Context mContext;
    private MoreDialogAdapter dialogAdapter;
    private Music mMusic;
    private MvsInfo mMvInfo;
    private int mMenuId;
    private int mType;

    private boolean needBuy = true;

    MusicManagerPresenter mPresenter;
    MoreDialogPresenter moreDialogPresenter;

    public static MoreDialog newInstance(Music music, int mMenuId, int mType) {
        MoreDialog fragment = new MoreDialog();

        Bundle bundle = new Bundle();
        bundle.putSerializable("music", music);
        bundle.putInt("menuId", mMenuId);
        bundle.putInt("managerType", mType);

        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void initPresenter() {
        mPresenter = new MusicManagerPresenter();
        mPresenter.attachModelView(new BaseModel(), this);

        moreDialogPresenter = new MoreDialogPresenter();
        moreDialogPresenter.attachModelView(new BaseModel(), this);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_FRAME, R.style.CustomDatePickerDialog);
        RxBus.get().register(this);
        mContext = getContext();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        initWindows();
        View view = inflater.inflate(R.layout.fragment_music_more, container);
        unbinder = ButterKnife.bind(this, view);
        initListData();
        initView();
        return view;
    }

    @Override
    public void onDestroy() {
        if (moreDialogPresenter != null) {
            moreDialogPresenter.dispose();
            moreDialogPresenter.onDetach();
        }
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        RxBus.get().unregister(this);
        unbinder.unbind();
        super.onDestroyView();
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        }
        getDialog().setCanceledOnTouchOutside(true);
    }

    private void initWindows() {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setAttributes(params);
    }

    private void initListData() {
        List<MoreBean> data = new ArrayList<>();
        int length;
        if (getArguments() != null) {
            mMusic = (Music) getArguments().getSerializable("music");
            mMenuId = getArguments().getInt("menuId");
            mType = getArguments().getInt("managerType");
        }

        if (mMusic == null) {
            return;
        }

        length = mMusic.getFileType() == Music.Type.LOCAL
                ? ICON.length
                : ICON.length - 1;

        for (int i = 0; i < length; i++) {
            MoreBean moreBean = new MoreBean(ICON_NAME[i], ICON[i]);
            data.add(moreBean);
        }
        dialogAdapter = new MoreDialogAdapter(data);
    }

    private void initView() {
        if (!Preferences.getLoginSn().isEmpty()) {
            moreDialogPresenter.getMusicInfo(mMusic);
        } else {
            moreButton.setText("立即登录");
            moreButton.setVisibility(View.VISIBLE);
            moreName.setText("登陆后可畅享更多功能");
            moreButton.setOnClickListener(v -> {
                dismiss();
                Intent login = new Intent(mContext, LoginRegisterActivity.class);
                mContext.startActivity(login);
            });
        }

        cancel.setOnClickListener(v -> dismiss());

        mRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 4));
        mRecyclerView.setAdapter(dialogAdapter);
        mRecyclerView.setHasFixedSize(true);
        dialogAdapter.setOnItemClickListener((adapter, view, position) -> {
            switch (position) {
                case 0:
                    addMusic();
                    dismiss();
                    break;
                case 1:
                    chatSinger();
                    dismiss();
                    break;
                case 2:
                    chatAlbum();
                    dismiss();
                    break;
                case 3:
                    chatMv();
                    break;
                case 4:
                    share();
                    break;
                case 5:
                    setDownMusic();
                    break;
                case 6:
                    addPlayList();
                    dismiss();
                    break;
                case 7:
                    startComment();
                    break;
                case 8:
                    setDelete();
                    break;
                default:
                    break;
            }
        });
    }

    private void chatMv() {
        if (mMusic.getMovieId() > 0 && mMvInfo != null) {
            PlayUtils.getMvPlayUrl(mMvInfo, mContext);
        } else {
            Toast.makeText(mContext, "该歌曲没有相关MV ", Toast.LENGTH_SHORT).show();
        }
        dismiss();
    }

    private void addMusic() {
        if (Preferences.getLoginSn().isEmpty()) {
            mContext.startActivity(new Intent(mContext, LoginRegisterActivity.class));
        } else {
            ArrayList<Integer> songIdList = new ArrayList<>();
            songIdList.add((int) mMusic.getSongId());
            CollectionDialog.newInstance(songIdList, IConstants.ONLINE).show(getFragmentManager(),
                    "CollectionDialog");
        }
    }

    private void chatSinger() {
        if (mMusic.getSongId() > 0) {
            Intent intent = new Intent(mContext, SingerInfoActivity.class);
            intent.putExtra("singerId", mMusic.getSingerId());
            mContext.startActivity(intent);
        } else {
            Toast.makeText(mContext, "该歌曲没有歌手", Toast.LENGTH_SHORT).show();
        }
    }

    private void chatAlbum() {
        if (mMusic.albumId > 0) {
            Intent catAlbum = new Intent(mContext, AlbumInfoActivity.class);
            catAlbum.putExtra("albumId", (int) mMusic.getAlbumId());
            mContext.startActivity(catAlbum);
        } else {
            Toast.makeText(mContext, "该歌曲没有专辑", Toast.LENGTH_SHORT).show();
        }
    }

    private void share() {
        moreDialogPresenter.getShareInfo(IConstants.SONG, (int) mMusic.getSongId(), getActivity());
    }

    private void setDownMusic() {
        if (DataBaseAccessor.getInstance().isExsitIdSyn(mMusic.getId(), DownloadStatus.DOWNLOAD_STATUS_COMPLETED)) {
            Toast.makeText(mContext, "该歌曲已经下载", Toast.LENGTH_SHORT).show();
        } else {
            if (!Preferences.getLoginSn().isEmpty()) {
                mMusic.setQuality(needBuy
                        ? IConstants.Common
                        : mMusic.getQualityType().get(0));
                downloadMusic(mMusic);
            } else {
                mContext.startActivity(new Intent(mContext, LoginRegisterActivity.class));
            }
        }
    }

    private void addPlayList() {
        if (mService != null) {
            mService.addMusicToPlayList(mMusic, mService.getPlayingPosition());
            ToastUtils.show(R.string.add_playlist_next_play);
        }
    }

    private void startComment() {
        Intent it = new Intent(mContext, CommentListActivity.class);
        it.putExtra("name", mMusic.getSongName());
        it.putExtra("artist", mMusic.getSingerName());
        it.putExtra("cover", mMusic.getCoverUri());
        it.putExtra("id", (int) mMusic.getSongId());
        it.putExtra("commentType", IConstants.SONG);
        mContext.startActivity(it);
        dismiss();
    }

    private void setDelete() {
        List<Integer> idList = new ArrayList<>();
        idList.add((int) mMusic.getSongId());
        showDeleteDialog(idList);
    }

    private void downloadMusic(Music music) {
        List<Music> downMusic = new ArrayList<>();
        music.setChecked(true);
        downMusic.add(music);
        mPresenter.getBatchDownId(downMusic);
    }

    @Override
    public void showDownTips(List<Music> downList) {
        UmengEventUtils.clickDownload(mContext, UmengEventUtils.SINGLE);
        mPresenter.reqDownMusic(downList, mMusic.getQuality(), mService);
    }

    @Override
    public void showDeleteDialog(List<Integer> deleteList) {
        DeleteDialog deleteDialog = new DeleteDialog(mContext, deleteList, (hasDownList, deleteFile) -> {
            mPresenter.deleteMusic(deleteList, hasDownList, mMenuId, mType, deleteFile);
        });

        deleteDialog.show();
    }

    @Override
    public void updateMusicInfoUI(Music music) {
        mMusic = music;
        if (mMusic.getMovieId() > 0) {
            moreDialogPresenter.getMvInfo(mMusic.getMovieId());
        }
        needBuy = false;
        moreName.setText(String.format("%s - %s", music.getSongName(), music.getSingerName()));
    }

    @Override
    public void updateMvInfoUI(MvsInfo mvsInfo) {
        mMvInfo = mvsInfo;
    }

    @Override
    public void setVipBuyUI() {
        dismiss();
    }

    @Subscribe(tags = {
            @Tag(RxBusEventType.SongMenu.DELETE_MENU_MUSIC),
            @Tag(RxBusEventType.Music.GET_DOWN_URL),
            @Tag(RxBusEventType.Music.SHARE)
    })
    public void onRxbusDeleteMenuMusic(RxbusListObject rxbusListObject) {
        dismiss();
    }
}
